package com.yitiao.multithread;

import lombok.SneakyThrows;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;

/**
 * @author libiao
 */
public class ThreadJoin {
    @SneakyThrows
    public static void main(String[] args) {
//        joinTest();
        futureTest();
    }

    @SneakyThrows
    private static void futureTest() {
        Thread t1 = new Thread(() -> {
            try {
                System.out.println("t1...");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1");
        t1.start();
//        t2.start();
        CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
            try {
                t1.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        });

        // do other things while waiting for t1 to finish
        System.out.println("Waiting for t1 to finish...");
//        Thread.sleep(1000);
        // 只等待指定时间
        future.get(1,TimeUnit.SECONDS);  // Exception in thread "main" java.util.concurrent.TimeoutException

        // t1 has finished, continue with other tasks
        System.out.println("t1 has finished, continuing with other tasks...");
    }

    private static void joinTest() throws InterruptedException {
        Thread t1 = new Thread(() -> {
            try {
                System.out.println("t1...");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }, "t1");
        t1.start();
        // 阻塞主线程，只有t1执行主线程才会继续执行，用来保证线程的执行顺序
        t1.join();

        System.out.println("t0");
        new Thread(()->{
            try {
                System.out.println("t2...");
                Thread.sleep(2000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        },"t2").start();
    }
}

